class Entry < ActiveRecord::Base
  validates_presence_of :title
  has_many :photos, :order => 'shot_date_time ASC, filename ASC'
  has_many :comments, :as => :commentable
  belongs_to :content_generator, :polymorphic => true

	def photos_by_datetime
		return Photo.entry_photos_by_datetime(self)
	end

	def update_photos_and_save
    if self.content_generator.photoblog_sourcedirs.include?(self.sourcedir)
      self.update_photos
      return self.save
    else
      return false
    end
	end

	def update_photos_and_attributes(params)
	  self.sourcedir = params[:sourcedir]
		self.update_photos
		return self.update_attributes(params)
	end

	def filenames_in_sourcedir
		d = Dir.new("public/#{self.sourcedir}")
		filenames = Array.new

		while filename = d.read do
			if Photo.valid_filename?(filename)
				filenames << filename
			end
		end
		return filenames
	end

	def purge_nonexistent_photos
	  files_that_exist = self.filenames_in_sourcedir
    self.photos.each do |photo|
      if !files_that_exist.include?(photo.filename)
				photo.destroy
			end
		end
	end

  def thumbnail
    thumbnails = self.photos.select do |photo|
      photo.is_entry_thumbnail
    end
    return (thumbnails.size > 0) ? thumbnails.first : self.photos.first
  end

	def update_photos
    photo = Array.new
		photo_filenames = self.filenames_in_sourcedir
		photo_filenames.each do |f|
			photo = Photo.get_existing(self, f) 
		  if photo == nil
				photo = Photo.new do |p|
					p.entry = self
					p.filename = f
					p.title = f
				end
			end
			photo.set_exif_data
      photos << photo
		end
    
    photos.sort! { |a,b| a.filename <=> b.filename }
    photos.each do |photo|
      photo.save
    end

		self.purge_nonexistent_photos
		self.size = self.photos.length
	end

	def Entry.sourcedir_is_associated? (sourcedir)
		return Entry.first(:conditions => ["sourcedir = ?", sourcedir]) != nil
	end

  def oldest_photo
    photos = self.photos.select { |p| p.shot_date_time != nil }
    photos.sort! { |a,b| b.shot_date_time <=> a.shot_date_time }
    return photos.first
  end

  def newest_photo
    photos = self.photos.select { |p| p.shot_date_time != nil }
    photos.sort! { |a,b| b.shot_date_time <=> a.shot_date_time }
    return photos.first
  end
end
